﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Collections;

namespace Crift
{

    public class StreamCipher
    {
        public Register Register1, Register2, Register3, Register4;
        public bool IsEqual(Register a, Register b)
        {
            for (int i = 0; i < a.InnerRegister.Length; i++) if (a.InnerRegister[i] != b.InnerRegister[i]) return false;
            return true;
        }
        public void ShiftRegistersRight()
        {
            Register1.ShiftRight();
            Register2.ShiftRight();
            Register3.ShiftRight();
            Register4.ShiftRight();
        }
        private BitArray GenerateKey(int KeyLength)
        {
            BitArray result = new BitArray(KeyLength);
            for (int i = 0; i < KeyLength; i++)
                result[i] = GenerateKeyBit();
            return result;
        }


        private bool GenerateKeyBit()
        {
            //F = (SR1 XOR SR2) XOR (SR2 AND SR3) XOR (SR3 AND SR4)

            bool Register1Bit = Register1.GetBit();
            bool Register2Bit = Register2.GetBit();
            bool Register3Bit = Register3.GetBit();
            bool Register4Bit = Register4.GetBit();
            return (Register1Bit ^ Register2Bit ^ (Register2Bit && Register3Bit) ^ (Register3Bit && Register4Bit));
        }

        public StreamCipher(string seed)
        {
            Register1 = new Register(seed.Substring(0, 4));
            Register2 = new Register(seed.Substring(0,4));
            Register3 = new Register(seed.Substring(0 ,4));
            Register4 = new Register(seed.Substring(0, 4));
        }

        public byte[] Encrypt(byte[] SrcData)
        {
            BitArray ContentBits = Conversions.ByteArrayToBitArray(SrcData);
            BitArray KeyBits = GenerateKey(SrcData.Length * 8);
            BitArray EncryptedDataBits = ContentBits.Xor(KeyBits);
            byte[] DstData = Conversions.BitArrayToByteArray(EncryptedDataBits);
            return DstData;


        }
    }
}